import co from "co";

const OSSConfig = {
  maxLength: 9,
  ossParams: {
    region: "oss-cn-shenzhen",
    endpoint: "http://oss-cn-shenzhen.aliyuncs.com",
    accessKeyId: "LTAI5tHB49bnyhXkFmPE1y8R",
    accessKeySecret: "emvWuTLi7Z1sFyuPeZHbXTxGtN5KGG",
    bucket: "dadingkunag",   
  }, 
};  

function random_string(len) {
  len = len || 32;
  var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz";
  var maxPos = chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

function timestamp() {
  return new Date().getTime();
}

/**
 *
 * @param event 上传图片的资源路径
 * @param type 图片资源类型
 * @param dir oss要保存的文件夹
 * @returns {OSS文件路径}
 */

function uploadOSS(event, type, dir = "file/") {
  return new Promise((resolve, reject) => {
    const OSS = require("ali-oss");
    var client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket,
    });
    var file;
    if (type == 0) {
      file = event;
    } else {
      file = event.target.files[0];
    }
    let randomName = `${dir}${random_string(6)}_${file.name}`;
    co(function* () {
      var result = yield client.multipartUpload(randomName, file);
   
      resolve(`${OSSConfig.uploadHost}/${result.name}`);
    }).catch(function (err) {
      console.log(err);
      reject(err);
    });
  });
}

function OSSupload(files, dir = "upload/") {
 

  return new Promise((resolve, reject) => {
    const OSS = require("ali-oss");
    var client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket,
    });

    const check = files.length > OSSConfig.maxLength;
    if (check) {
      console.log("最多只能上传" + OSSConfig.maxLength + "张图片。");
      return false;
    }

    var names = [];
    var urls = [];
    
    co(function* () {
        let list = []
      for (let i = 0; i < files.length; i++) {
        console.log(files);

        let url = "upload/" + timestamp() + "-Ryan-" + files[i].name;
        // https://dadingkunag.oss-cn-shenzhen.aliyuncs.com/upload/1691114802502-Ryan-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230426143751.jpg
        urls.push(
          "https://dadingkunag.oss-cn-shenzhen.aliyuncs.com/" + url  
        );
       
        if (isImage(files[i].name)) {
           
          resizeImage({
            file: files[i],
            maxSize: 1200,
            rate: 0.7,
          })
            .then( (resizedImage)=>{
               
              client
                .put(url, resizedImage)
                .then((res) => {
                    console.log(res,999);
                    // list.push({name:res.name,url:res.url})
                    if(res){
                        
                    }
                 
                  
                })
                .catch((err) => {
                  
                  reject(files[i].name + "上传失败");
                });
            })
            .catch( (e)=> {
              console.log(e);
            });
        } else {
          client
            .put(url, files[i])
            .then((res) => {
              //console.log(res)
            })
            .catch((err) => {
              console.log(err);
              reject(files[i].name + "上传失败");
            });
        }
      }
    });
    resolve(urls);
   
  });
}

function OSSDelete(url) {
  return new Promise((resolve, reject) => {
    const OSS = require("ali-oss");
    var client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket,
    });

    client
      .delete(url)
      .then((res) => {
        console.log("删除成功");
        resolve(res);
      })
      .catch((err) => {
        console.log("删除失败");
        reject(e);
      });
  });
}

function OSSDeleteMulti(urls) {
  return new Promise((resolve, reject) => {
    const OSS = require("ali-oss");
    var client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      bucket: OSSConfig.ossParams.bucket,
    });

    client
      .deleteMulti(urls)
      .then((res) => {
        console.log("批量删除成功");
        resolve(res);
      })
      .catch((err) => {
        console.log("批量删除失败");
        reject(err);
      });
  });
}

function isImage(name) {
  if (
    name.indexOf(".jpg") > -1 ||
    name.indexOf(".jpeg") > -1 ||
    name.indexOf(".png") > -1 ||
    name.indexOf(".PNG") > -1 ||
    name.indexOf(".JPEG") > -1 ||
    name.indexOf(".JPG") > -1
  ) {
    return true;
  } else {
    return false;
  }
}

// 压缩图片
function resizeImage(settings) {
  var file = settings.file;
  var maxSize = settings.maxSize;
  var rate = settings.rate;
  var reader = new FileReader();
  var image = new Image();
  var canvas = document.createElement("canvas");
  var dataURItoBlob = function (dataURI) {
    var bytes =
      dataURI.split(",")[0].indexOf("base64") >= 0
        ? atob(dataURI.split(",")[1])
        : unescape(dataURI.split(",")[1]);
    var mime = dataURI.split(",")[0].split(":")[1].split(";")[0];
    var max = bytes.length;
    var ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], { type: mime });
  };
  var resize = function () {
    var width = image.width;
    var height = image.height;
    if (width > height) {
      if (width > maxSize) {
        height *= maxSize / width;
        width = maxSize;
      }
    } else {
      if (height > maxSize) {
        width *= maxSize / height;
        height = maxSize;
      }
    }
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(image, 0, 0, width, height);
    var dataUrl = canvas.toDataURL("image/jpeg", rate);
    window.URL.revokeObjectURL(image.src);
    return dataURItoBlob(dataUrl);
  };
  return new Promise(function (ok, no) {
    // if (!file.type.match(/image.*/)) {
    //     no(new Error("Not an image"));
    //     return;
    // }
    reader.onload = function (readerEvent) {  
      image.onload = function () {
        return ok(resize());
      };
      image.src = readerEvent.target.result;
    };
    var blob = new Blob([file]);
    reader.readAsDataURL(blob);
  });
}

export { OSSupload, OSSDelete };
